﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Autofac;
using Ledict.ConditionExtract.BLL;
using Ledict.ConditionExtract.DAL;
using Ledict.Core.Data;
using Microsoft.Practices.ServiceLocation;

namespace Ledict.ConditionExtract.Base
{
    /// <summary>
    /// Autofac注册
    /// </summary>
    public class AutofacRegister
    {
        /// <summary>
        /// 依赖注入autofac
        /// </summary>
        public static void RegisterMain()
        {
            //var builder = new ContainerBuilder();
            ////注册服务获取类
            //builder.RegisterType<ServiceGetter>().As<IServiceGetter>();
            //builder.RegisterType<IUnitOfWork>().As<IUnitOfWork>();

            //// 获取所有相关类库的程序集
            //var assemblys = new List<Assembly>
            //{
            //    Assembly.GetExecutingAssembly(), //web 对Controller进行依赖注入
            //    typeof (AboutRegexBLL).Assembly, //Service
            //    typeof (AboutRegexDAL).Assembly //Dao
            //    //typeof().Assembly
            //}.ToArray();

            ////builder.RegisterGeneric(typeof(Repository<,>)).As(typeof(IRepository<,>));


            ////注册assemblys程序集
            //RegisterAssemblys(builder, assemblys);
            //var container = builder.Build();
            ////DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); //mvc注册

            ////利用统一服务定位器进行注入
            ////todo by zhangpeng:解耦依赖注入框架和项目间关系，以后可以灵活利用autofac、unity等注入框架，而不需要改动各实现类
            //ServiceLocator.SetLocatorProvider(() => new AutofacServiceLocator(container));

            //测试
            //var serviceObject = ServiceLocator.Current.GetInstance<ITestBll>();
            //serviceObject.Write();
        }

        /// <summary>
        ///     注册程序集(多个)
        /// </summary>
        /// <param name="builder">容器</param>
        /// <param name="assembly">程序集（多个）</param>
        private static void RegisterAssemblys(ContainerBuilder builder, Assembly[] assembly)
        {
            //注册以Manager或Dao结尾的类
            //builder.RegisterAssemblyTypes(assembly)
            //    .Where(x => (x.Name.EndsWith("Manager") || x.Name.EndsWith("Dao")) && !x.IsInterface)
            //    .AsImplementedInterfaces()
            //    .InstancePerLifetimeScope();

            //var baseType = typeof(IDependency);

            ////注册继承IDependency接口的类
            //builder.RegisterAssemblyTypes(assembly)
            //    .Where(x => baseType.IsAssignableFrom(x) && !x.IsInterface)
            //    .AsImplementedInterfaces()
            //    .InstancePerLifetimeScope();

            //注册控制器
            //builder.RegisterControllers(assembly);
        }
    }
}
